<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptions">
      <template #form="{ form }">
        <VSelect v-model="form.platform_ids" placeholder="平台" :options="options.platform" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.shop_ids" placeholder="店铺" :options="options.shop" multiple collapse-tags style="min-width: 160px" confusedPaste paste />
        <VSelect v-model="form.regions" placeholder="地区" :options="options.region" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.brand_types" placeholder="商标类型" :options="options.brand_type" multiple collapse-tags style="min-width: 160px" />
        <VGroup class="inline-block">
          <span class="v-group-item inline-block leading-8 align-middle">持有主体</span>
          <VSelect v-model="form.holder_type" placeholder="持有主体" :options="options.holder_type" style="width: 80px" :clearable="false" select @change="form.holder = []" />
          <VSelect v-if="form.holder_type === 1" v-model="form.holder" :options="options.company_id" placeholder="请选择" multiple collapse-tags style="min-width: 200px" />
          <VCascader v-else-if="form.holder_type === 2" v-model="form.holder" placeholder="请选择" multiple collapse-tags style="min-width: 200px" />
          <el-input v-else v-model="form.holder[0]" placeholder="请输入" class="inline" style="min-width: 200px" />
        </VGroup>
        <VGroup class="inline-block">
          <span class="v-group-item inline-block leading-8 align-middle">历史持有主体</span>
          <VSelect v-model="form.history_holder_type" placeholder="历史持有主体" :options="options.holder_type" style="width: 80px" :clearable="false" select
            @change="form.history_holder = []" />
          <VSelect v-if="form.history_holder_type === 1" v-model="form.history_holder" :options="options.company_id" placeholder="请选择" multiple collapse-tags
            style="min-width: 200px" />
          <VCascader v-else-if="form.history_holder_type === 2" v-model="form.history_holder" placeholder="请选择" multiple collapse-tags style="min-width: 200px" />
          <el-input v-else v-model="form.history_holder[0]" placeholder="请输入" class="inline" style="min-width: 200px" />
        </VGroup>
        <VCascader v-model="form.create_ids" placeholder="创建人" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.statuses" placeholder="状态" :options="options.status" multiple collapse-tags style="min-width: 160px" />
        <VGroup>
          <el-select v-model="form.dateRange.type" style="width: 120px">
            <el-option label="截止时间" value="deadline_date"></el-option>
            <el-option label="合同时间" value="contract_date"></el-option>
            <el-option label="下R标时间" value="r_mark_date"></el-option>
            <el-option label="下TM标时间" value="tm_mark_date"></el-option>
          </el-select>
          <el-date-picker v-model="form.dateRange.value" type="daterange" value-format="YYYY-MM-DD" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
            style="max-width: 260px" />
        </VGroup>
        <VGroup>
          <el-select v-model="form.input.type" style="width: 100px">
            <el-option label="商标名称" value="brand_name"></el-option>
            <el-option label="序列号" value="sequence_number"></el-option>
            <el-option label="注册号" value="registration_number"></el-option>
            <el-option label="机构名称" value="agency"></el-option>
          </el-select>
          <el-input v-model="form.input.value" placeholder="请输入" class="w-60" />
        </VGroup>
      </template>
      <template #toolbar_btns>
        <VButton auth="/base/brand/create" type="primary" icon="DocumentAdd" @click="create(tableRef)">添加</VButton>
        <VButton auth="/base/brand/delete" @click="handleBatch('delete')">删除</VButton>
        <VImport :tableRef="tableRef" importUrl="/v1/brand/import" v-if="authList.includes('/base/brand/import')"
          downloadUrl="https://xc-base.oss-cn-shenzhen.aliyuncs.com/template/brand.xlsx" class="ml-auto" />
        <VExport auth="/base/brand/export" mainKey="brand_id" name="brand" :tableRef="tableRef" task />
      </template>
    </VTable>
    <Add ref="addRef" :options="options" @success="query" />
    <VLog ref="logRef" />
    <Bind ref="bindRef" />
    <ViewImage ref="viewImageRef" />
  </VPage>
</template>
  
<script setup lang="jsx" name="Account">
import api from './api'
import Add from './components/Add'
import Bind from './components/Bind'
import VImport from '@/components/VImport'
import { getOption } from '@/api/public'
import { ElMessage, ElMessageBox } from 'element-plus'

const baseName = 'brand'
const tableRef = ref()
const logRef = ref()
const loadings = reactive({})
const viewImageRef = ref()
// 查询
const query = () => {
  tableRef?.value.query()
}

const authList = window.BTN_AUTH || []

// 新增
const addRef = ref()
const create = () => {
  addRef?.value.open()
}

// 获取options
const options = ref({})
Promise.all([
  getOption({ type: baseName }).then(res => res.data),
  Promise.resolve({ test: [{ label: '没有数据', value: 1 }] })
]).then(res => {
  options.value = res.reduce((acc, cur) => (((acc = { ...acc, ...cur }), acc)), {})
})

// 批量操作
const handleBatch = (name) => {
  const selection = tableRef.value.$table.getCheckboxRecords()
  if (!selection.length) {
    ElMessage.warning('请先选择行')
    return
  }
  const brand_ids = selection.map(d => d.brand_id)
  const showLoading = () => loadings[name] = true
  const closeLoading = () => loadings[name] = false
  const handle = {
    delete: () => {
      ElMessageBox.confirm('是否确认删除？', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(() => {
          showLoading()
          api.delete({ brand_ids }).then(res => {
            ElMessage({ type: 'success', message: '操作成功', })
            query()
          }).finally(closeLoading)
        })
        .catch(() => {
          ElMessage({ type: 'info', message: '取消操作', })
        })
    },
  }
  handle[name]()
}
// 单行操作
const bindRef = ref()
const handleRow = (name, row, rowIndex) => {
  const { brand_id } = row
  const showLoading = (name = 'handle') => {
    loadings[name + rowIndex] = true
  }
  const closeLoading = (name = 'handle') => {
    loadings[name + rowIndex] = false
  }
  const handle = {
    edit: () => {
      addRef?.value.open(brand_id)
    },
    delete: () => {
      ElMessageBox.confirm('是否确认删除？', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(() => {
          showLoading()
          api.delete({ brand_ids: [brand_id] }).then(res => {
            ElMessage({ type: 'success', message: '操作成功', })
            query()
          }).finally(closeLoading)
        })
        .catch(() => {
          ElMessage({ type: 'info', message: '取消操作', })
        })
    },
    bind: () => {
      bindRef?.value.open(brand_id)
    },
    log: () => {
      logRef?.value.open({ type: baseName, record_id: brand_id })
    },
  }
  handle[name]()
}

// 列表配置
const tableOptions = reactive({
  rowConfig: { height: 116 },
  showHeaderOverflow: false,
  formConfig: {
    data: {
      holder_type: 1,
      history_holder_type: 1,
      input: { type: 'brand_name', value: '' }, // 组合
      brand_types: [],
      dateRange: { type: 'deadline_date', value: [], range: true }, // 组合
    }
  },
  columns: [
    { type: 'checkbox', fixed: 'left', width: 40 },
    { type: 'seq', fixed: 'left', width: 50, slots: { header: () => '序号' } },
    {
      minWidth: 200, slots: {
        header: [
          {title: '商标名称', sort: 'brand_name'},
          {title: '序列号', sort: 'sequence_number'},
          {title: '注册号', sort: 'registration_number'},
        ],
        default: ({ row }) => < div >
          <VText value={row.brand_name} />
          <VText value={row.sequence_number} />
          <VText value={row.registration_number} />
        </div >
      }
    },
    {
      minWidth: 100, slots: {
        header: () => '商标图片',
        default: ({ row }) => <el-image src={row.brand_image} />
      }
    },
    {
      title: '状态', minWidth: 100, sortable: true, slots: {
        default: ({ row }) => row.status
      }
    },
    { title: '商标类型', field: 'brand_type', minWidth: 100, sortable: true },
    { title: '商标类别', field: 'category', minWidth: 100, sortable: true },
    {
      title: '地区', field: 'region', minWidth: 100, sortable: true, slots: {
        default: ({ row }) => <VText value={row.region} line={3} />
      }
    },
    {
        minWidth: 200, slots: {
        header: () => <div>
          日期
          <VSort value={[
            {label: '提交申请日期', value: 'submit_apply_date'},
            {label: '下R标日期', value: 'r_mark_date'},
            {label: '下TM标时间', value: 'tm_mark_date'},
            {label: '合同日期', value: 'contract_date'},
            {label: '截止日期', value: 'deadline_date'},
          ]} dropdown class='ml-1' />
        </div>,
        default: ({ row }) => < div >
          <VText title='提交申请日期' value={row.submit_apply_date} />
          <VText title='下R标日期' value={row.r_mark_date} />
          <VText title='下TM标时间' value={row.tm_mark_date} />
          <VText title='合同日期' value={row.contract_date} />
          <VText title='截止日期' value={row.deadline_date} />
        </div >
      }
    },
    {
      field: 'certificate', minWidth: 220, slots: {
        header: () => '证书',
        default: ({ row, rowIndex }) => {
          return <VMore key={rowIndex}>
            {{
              default: (line) => (row.certificate || []).map(d => <div class='w-full'>
                <VText value={d.file_name} line={1} type='link' onClick={() => viewImageRef?.value.open(d.file_url)} />
              </div>)
            }}
          </VMore>
        }
      }
    },
    { title: '持有主体', field: 'holder_text', minWidth: 160, line: 3, sortable: true },
    { title: '使用部门', field: 'use_department', minWidth: 120, line: 2, sortable: true },
    {
      title: '关联店铺', field: 'assoc_shops', minWidth: 100, sortable: true, slots: {
        default: ({ row }) => row.assoc_shops ? (authList.includes('/base/brand/shop-list') ? <el-button link type='primary' onClick={() => handleRow('bind', row)}>{row.assoc_shops}</el-button> : row.assoc_shops) : 0
      }
    },
    {
      title: '代理/办理机构', field: 'agency', minWidth: 140, sortable: true, slots: {
        default: ({ row }) => <VText value={row.agency} line={3} />
      }
    },
    {
      title: '费用', field: 'fee', minWidth: 140, sortable: true, slots: {
        default: ({ row }) => row.fee
      }
    },
    {
      title: '使用商品（商标小类）', field: 'goods_used', minWidth: 120, line: 3, sortable: true
    },
    // { title: '创建人', field: 'create_user', minWidth: 120 },
    // { title: '创建时间', field: 'create_time', minWidth: 170 },
    {
      title: '备注', field: 'remark', minWidth: 120, slots: {
        default: ({ row }) => <VText value={row.remark} line={3} />
      }
    },
    {
      title: '操作', width: 110, fixed: 'right', slots: {
        default: ({ row, rowIndex }) => {
          return <div class='nm flex flex-wrap gap-1'>
            <VButton auth="/base/brand/edit" link type="primary" onClick={() => handleRow('edit', row)}>编辑</VButton>
            <VButton auth="/base/brand/delete" link type="danger" onClick={() => handleRow('delete', row, rowIndex)}>删除</VButton>
            <VButton auth="/base/brand/log" link type="primary" onClick={() => handleRow('log', row)} class='m-0'>日志</VButton>
          </div>
        }
      }
    }
  ],
  proxyConfig: {
    ajax: {
      query: ({ page, form }) => api.query({ ...form, ...page })
    }
  }
})
</script>
  